package com.thinking.dubbo.redis.user;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.annotation.PostConstruct;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class UserRedisActuator {

    @Autowired
    private RequestMappingHandlerMapping requestMappingHandlerMapping;
    @Autowired
    private UserRedisTemplate<String, Object> userRedisTemplate;


    @PostConstruct
    void init() {
        try {
            RequestMappingInfo mapping = RequestMappingInfo.paths("/actuator/redis/user/test").methods(RequestMethod.GET).build();
            Method method = UserRedisActuator.class.getDeclaredMethod("test");
            requestMappingHandlerMapping.registerMapping(mapping, this, method);
        } catch (Throwable e) {
            log.error("redis.user.test.register.error.", e);
        }
    }

    @ResponseBody
    Map<String, Object> test() {
        String key = "redis:user:test";
        userRedisTemplate.opsForValue().set(key, "user-test-"+System.currentTimeMillis());
        Map<String, Object> map = new HashMap<>();
        map.put(key, userRedisTemplate.opsForValue().get(key));
        return map;
    }

}
